package com.sskj.trafficcontrol.web.filter;

import com.sskj.trafficcontrol.util.RequestUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;


/**\
 * @Filter
 */
@Component
@WebFilter(urlPatterns = "/*", filterName = "rest0PubFilter")
public class Rest0PubFilter implements Filter {
    private static Logger LOGGER = LoggerFactory.getLogger(Rest0PubFilter.class);

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;

        String clientIp = RequestUtil.getClientIp(request);
        String uri = request.getRequestURI();
        String encoding = request.getCharacterEncoding();
        String scheme = request.getScheme();
        LOGGER.info("Rest0PubFilter ip={} encoding={} scheme={} uri={}", clientIp, encoding, scheme, uri);

        /*if(!"OPTIONS".equals(request.getMethod().toUpperCase())) {//避免跨越

        }*/

        filterChain.doFilter(request, response);//doFilter将请求转发给过滤器链下一个filter , 如果没有filter那就是你请求的资源

    }

    @Override
    public void destroy() {
    }

    private static String headerValuesToString(Collection<String> values) {
        if (values == null || values.size() == 0) {
            return "";
        }
        StringBuilder buf = new StringBuilder();
        int i = 0;
        for (String value : values) {
            if (i > 0) {
                buf.append(", ");
            }
            buf.append(value);
            i++;
        }
        return buf.toString();
    }
}
